package com.lagou.rpc.provider.server;

import com.lagou.rpc.provider.handler.RpcServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Desc    启动类
 * @Author Matures
 * @CreateTime 2021/4/10 22:11
 **/
@Component
public class RpcServer implements DisposableBean {

    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workerGroup;

    @Autowired
    private RpcServerHandler rpcServerHandler;

    public void startServer(String ip, int port) throws InterruptedException {
        // 1.创建线程组
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        // 2.创建服务端启动助手
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 3.设置参数
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 添加String类型的编解码器
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        // 业务处理类 todo
                        pipeline.addLast(rpcServerHandler);
                    }
                });
        // 4.绑定端口
        ChannelFuture sync = serverBootstrap.bind(ip, port).sync();
        System.out.println("服务端启动成功");

        // 注册到zookeeper
        registerZookeeper(ip,port);
        sync.channel().closeFuture();
    }

    /**
     * 将此服务端注册到zookeeper节点
     */
    private void registerZookeeper(String ip, int port) {
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        System.out.println("2号服务器-会话创建成功");

        zkClient.createEphemeral("/lg-rpc/server-2",ip+":"+port);
        System.out.println("2号服务器-节点创建成功");
    }

    @Override
    public void destroy() throws Exception {
        if(bossGroup != null){
            bossGroup.shutdownGracefully();
        }
        if(workerGroup != null){
            workerGroup.shutdownGracefully();
        }
    }
}
